App.controller('scheduleController', ['$rootScope','$scope','$http','Page',	function($rootScope, $scope, $http, Page) {
	
	$scope.tabs = [
        {
        	idx : '1',
            name : "车辆资源",
            url : "views/media/schedule_bus.html"
        },
        {
        	idx : '2',
            name : "站点资源",
            url : "views/media/schedule_stop.html"
        }
    ];
	
	$scope.initTab = function(tabIdx){
		$scope.$broadcast('tabIdx', tabIdx);
	}
	
	//资源明细
	$scope.resourceInfoModal = {
		open : function(resource){
			this.resource = resource;
			this.show();
		},
		onShow : function(){
			if(!this.resource.mediaItems){
				Page.ajaxPostQuiet('mediaType/' + this.resource.mediaType + '/items.do', null, function (resp) {
				 	$scope.resourceInfoModal.resource.mediaItems = resp.data;
				});
			}
			$("#resourceImgViewArea").attr("src",$rootScope.nginxPath + this.resource.resourceImg);
			
			$scope.resourceAdsGrid.query({resourceId:this.resource.resourceId});
			$scope.resourceRightsGrid.query({resourceId:this.resource.resourceId});
		}
	};
	
	$scope.resourceAdsGrid = {
		options : {
			lazy : true
		}
	};
	
	$scope.resourceRightsGrid = {
		options : {
			lazy : true
		}
	};
	//排期
	$scope.scheduleInfoTip = {
		open : function(data,schedule){
			this.scheduleData = data;
			this.scheduleData.schedule = schedule;
			if(schedule.status != 'free'){//空闲不弹框
				this.show(event);
			}
		},
		showContract : function(){
			$scope.contractResourceModel.open(this.scheduleData.schedule.contract.contractId);
			this.hide();
		},
		showAdContent : function(){
			adInfoModel.open(this.scheduleData.schedule.bill.content, this.scheduleData.schedule.bill.publishImg);
			this.hide();
		}
	};
	
	//广告内容
	$scope.adInfoModel = {
		open : function(content,adImg,billId,resourceId){
			this.content = content;
			this.adImg = adImg;
			this.billId = billId;
			this.resourceId = resourceId;
		},
		onShow : function(){
			this.setTitle('广告内容- ' + this.content);
			$("#contentImgArea").attr("src",$rootScope.nginxPath + this.adImg); 
		}	
	}	

	//合同明细
	$scope.contractResourceModel = {
		open : function(contractId){
			this.contractId = contractId;
			this.show();
		},
		onShow : function(){
			Page.ajaxGetQuiet('contract/'+this.contractId+'/info.do',null, function (resp) {
				var contract = resp.data;
				$scope.contractResourceModel.setTitle('合同明细 -- ' + contract.contractNo);
	    		$scope.contractResourceModel.contract = resp.data;
	    				
	    		contract.mediasMap = new Map();
		        Page.ajaxGetQuiet('contract/' + contract.contractId + '/resources.do',null, function (resp) {
		        	$(resp.data).each(function(index, resource) {
		            	var mediaType = resource.mediaType;
		                var mediaName = resource.mediaName;
		                var parentMedia = resource.parentMedia;
						var resources = contract.mediasMap.get(mediaType) ||
										{
											mediaType:mediaType,
											mediaName:mediaName,
											parentMedia:parentMedia,
											data:[]
										};
						resources.data.push(resource);
						contract.mediasMap.put(mediaType, resources);
					});
		     	});
	    	});
		}
	};
	

	
	//上刊单明细

    $scope.billDetailsGrid = {
			options : {
				lazy : true
			}
	}
    $scope.billResourcModel = {
			onShow : function(){
				this.setTitle('上刊单明细 -- ' +$scope.scheduleData.schedule.bill.billNo);
			},
			showBillRes : function() {
				 $scope.scheduleInfo.hide();
				 $scope.billDetailsGrid.query.billId =  $scope.scheduleData.schedule.bill.billId;
				 $scope.billDetailsGrid.query();
		         $scope.billResourcModel.show();
		     }
	}

	
} ]);

App.controller('busScheduleController', ['$rootScope','$scope','$http','Page',	function($rootScope, $scope, $http, Page) {
	
	$scope.resourceType = "1";
	
	Page.ajaxGetQuiet('media/bus/mediatypes.do', null, function (resp) {
        $scope.busMedias = resp.data;
    });
	
	Page.ajaxPostQuiet('media/bus/companys.do', null, function (resp) {
    	  $scope.companys = resp.data;
    });
	
	Page.ajaxPostQuiet('busType/query.do', null, function (resp) {
        $scope.busTypes = resp.data;
    });
	
	$scope.scheduleQuery = {
		mediaType:''
	};
	
	$scope.query = function(month,lastOrNext, monthOrYear) {
		var param = {};
		param.month = month;// 当前月份
		param.lastOrNext = lastOrNext;// -1：上一月 上一年 1：下一月 下一年
		param.monthOrYear = monthOrYear;// 1:年 2：月
		param.pageIndex = 0;
		param.pageSize = 20;
		
		param.resourceType = $scope.resourceType;//父类型
		param.mediaType = $scope.scheduleQuery.mediaType;//子类型
		param.resourceCode = $scope.scheduleQuery.resourceCode;
		param.companyId = $scope.scheduleQuery.companyId;
		param.lineNo = $scope.scheduleQuery.lineNo;
		param.plateNo = $scope.scheduleQuery.plateNo;
		param.vehicleNo = $scope.scheduleQuery.vehicleNo;
		param.busType = $scope.scheduleQuery.busType;
		param.busFloor = $scope.scheduleQuery.busFloor;
		param.airConditioned = $scope.scheduleQuery.airConditioned;
		param.busEnergy = $scope.scheduleQuery.busEnergy;
		param.businessType = $scope.scheduleQuery.businessType;
		param.status = $scope.scheduleQuery.status;
		
		Page.ajaxPost('schedule/query.do', param, function(resp) {
			$scope.months = resp.data.months;
			$scope.days = resp.data.daysArray;
			$scope.dataArray = resp.data.dataArray;
			$scope.monthSelect = resp.data.currentMonth;
			$scope.lastYear = resp.data.lastYear;
			$scope.nextYear = resp.data.nextYear;
			$scope.totalPages = resp.data.totalPages;
			$scope.currentMonth = resp.data.currentMonth;
				// 调用分页
				laypage({
					cont : 'page_bar',
					pages : $scope.totalPages,// 得到总页数
					skin : '#12bdce',
					skip : true, // 是否开启跳页
					prev : '<', // 若不显示，设置false即可
					next : '>', // 若不显示，设置false即可
					groups : 5, //连续分页数
					curr: 1, //初始化当前页
					jump : function(obj,first) {// 触发分页后的回调
						/*obj是一个object类型。包括了分页的所有配置信息。
						 first一个Boolean类，检测页面是否初始加载。非常有用，可避免无限刷新。*/
						if(!first){
							//var param = {};
							param.month = $scope.currentMonth;// 当前月份
							param.pageIndex = obj.curr - 1;
							param.pageSize = 20;
								Page.ajaxPost('schedule/query.do', param, function(resp) {
									$scope.months = resp.data.months;
									$scope.days = resp.data.daysArray;
									$scope.dataArray = resp.data.dataArray;
									$scope.monthSelect = resp.data.currentMonth;
									$scope.lastYear = resp.data.lastYear;
									$scope.nextYear = resp.data.nextYear;
									$scope.totalPages = resp.data.totalPages;
									$scope.currentMonth = resp.data.currentMonth;
								});
						}
					}
				})
		});
	};
	
	$scope.$watch('busMedias', function (newValue, oldValue, $scope) {
		if(newValue){
			$scope.scheduleQuery.mediaType = $scope.busMedias[0].mediaId;
			$scope.query();
		}
	});
	//
	$scope.mediaTypeChange = function(mediaType) {
		$scope.scheduleQuery.mediaType = mediaType;
		$scope.query();
	}
	
	//选择月份
	$scope.monthChange = function(month) {
		$scope.query(month);
	};
	
	$scope.busMediaInfoModal = {
		open : function(busId){
			this.busId = busId;
			this.show();
		},
		onShow : function(){
			var mapDiv = "busMediaInfoModalMapDiv";
			var width = $('#' + mapDiv).width();
			var height = $('#' + mapDiv).height();
			this.map = new AMap.Map(mapDiv, {resizeEnable: true,zoom:12});
			
			Page.ajaxGetQuiet('media/bus/' + this.busId + '/info.do', null, function (resp) {
				$scope.busMediaInfoModal.mediaBus = resp.data;
				$($scope.busTypes).each(function(index, type) {
					if(type.typeId == $scope.busMediaInfoModal.mediaBus.busType){
						$scope.busMediaInfoModal.mediaBus.busTypeName = type.typeName;
					}
				});
				Page.ajaxGetQuiet('media/bus/' + $scope.busMediaInfoModal.mediaBus.busId + '/marks.do', null, function (resp) {
					$scope.busMediaInfoModal.mediaBus.marks = resp.data;
				});
				$("#busMediaInfoModalImgViewArea").attr("src",$rootScope.nginxPath + $scope.busMediaInfoModal.mediaBus.busImg);
				
				//地图线路
				if($scope.busMediaInfoModal.mediaBus.lineNo){
					AMap.service(["AMap.LineSearch"], function() {
					    var linesearch = new AMap.LineSearch({
					    	city:'027',
					    	extensions:'all'
					    });
					    linesearch.search($scope.busMediaInfoModal.mediaBus.lineNo, function(status, result) {
				            if (status === 'complete' && result.info === 'OK' && result.lineInfo.length > 0) {
				              	var busArr = result.lineInfo[0].path;
		                		var stops = result.lineInfo[0].via_stops;
		                		var startPot = stops[0].location;
		                		var endPot = stops[stops.length - 1].location;
		                		
		                		new AMap.Marker({
						            map: $scope.busMediaInfoModal.map,
						            position: [startPot.lng, startPot.lat], //基点位置
						            icon: "http://webapi.amap.com/theme/v1.3/markers/n/start.png",
						            zIndex: 10
						        });
						        new AMap.Marker({
						            map: $scope.busMediaInfoModal.map,
						            position: [endPot.lng, endPot.lat], //基点位置
						            icon: "http://webapi.amap.com/theme/v1.3/markers/n/end.png",
						            zIndex: 10
						        });
						        //绘制乘车的路线
						        busPolyline = new AMap.Polyline({
						            map: $scope.busMediaInfoModal.map,
						            path: busArr,
						            strokeColor: "#09f",//线颜色
						            strokeOpacity: 0.8,//线透明度
						            strokeWeight: 5//线宽
						        });
						        
						        var mstop = stops[parseInt(stops.length/2)];
						        $scope.busMediaInfoModal.map.setCenter([mstop.location.lng, mstop.location.lat]);
				            }
				    	});
					});
				}
				
//				if($scope.busMediaInfoModal.mediaBus.lineNo){
//					var busPosition = {};
//					new AMap.Marker({
//						 map: $scope.busMediaInfoModal.map,
//						 position: [busPosition.lng, busPosition.lat], 
//						 icon: "http://webapi.amap.com/theme/v1.3/markers/n/end.png",
//						 zIndex: 10
//					});
//				}
				
				
				
			});
			
   		}
	};
	
} ]);

App.controller('stopScheduleController', ['$rootScope','$scope','$http','Page',	function($rootScope, $scope, $http, Page) {
	$scope.resourceType = "2";
	
	Page.ajaxGetQuiet('media/stop/mediatypes.do', null, function (resp) {
        $scope.stopMedias = resp.data;
    });
	
	$scope.$watch('stopMedias', function (newValue, oldValue, $scope) {
		if(newValue){
			$scope.scheduleQuery.mediaType = $scope.stopMedias[0].mediaId;
		}
	});
	
	$scope.scheduleQuery = {};
	
	$scope.query = function(month,lastOrNext, monthOrYear) {
		var param = {};
		param.month = month;// 当前月份
		param.lastOrNext = lastOrNext;// -1：上一月 上一年 1：下一月 下一年
		param.monthOrYear = monthOrYear;// 1:年 2：月
		param.pageIndex = 0;
		param.pageSize = 20;
		param.resourceName = $scope.scheduleQuery.resourceName;
		param.resourceCode = $scope.scheduleQuery.resourceCode;
		param.resourceType = $scope.resourceType;//父类型
		param.mediaType = $scope.scheduleQuery.mediaType;//子类型
		param.county = $scope.scheduleQuery.county;
		param.roadName = $scope.scheduleQuery.roadName;
		param.stopName = $scope.scheduleQuery.stopName;
		Page.ajaxPost('schedule/query.do', param, function(resp) {
			$scope.months = resp.data.months;
			$scope.days = resp.data.daysArray;
			$scope.dataArray = resp.data.dataArray;
			$scope.monthSelect = resp.data.currentMonth;
			$scope.lastYear = resp.data.lastYear;
			$scope.nextYear = resp.data.nextYear;
			$scope.totalPages = resp.data.totalPages;
			$scope.currentMonth = resp.data.currentMonth;
				// 调用分页
				laypage({
					cont : 'stop_page_bar',
					pages : $scope.totalPages,// 得到总页数
					skin : '#12bdce',
					skip : true, // 是否开启跳页
					prev : '<', // 若不显示，设置false即可
					next : '>', // 若不显示，设置false即可
					groups : 5, //连续分页数
					curr: 1, //初始化当前页
					jump : function(obj,first) {// 触发分页后的回调
						/*obj是一个object类型。包括了分页的所有配置信息。
						 first一个Boolean类，检测页面是否初始加载。非常有用，可避免无限刷新。*/
						if(!first){
							//var param = {};
							param.month = $scope.currentMonth;// 当前月份
							param.pageIndex = obj.curr - 1;
							param.pageSize = 20;
								Page.ajaxPost('schedule/query.do', param, function(resp) {
									$scope.months = resp.data.months;
									$scope.days = resp.data.daysArray;
									$scope.dataArray = resp.data.dataArray;
									$scope.monthSelect = resp.data.currentMonth;
									$scope.lastYear = resp.data.lastYear;
									$scope.nextYear = resp.data.nextYear;
									$scope.totalPages = resp.data.totalPages;
									$scope.currentMonth = resp.data.currentMonth;
								});
						}
					}
				})
		});
	}
	
	$scope.$on('tabIdx', function(event,tabIdx) {
		if(!$scope.initflag && tabIdx == $scope.resourceType){
			$scope.query();
			$scope.initflag = true;
		}	  
	});
	
	$scope.mediaTypeChange = function(mediaType) {
		$scope.scheduleQuery.mediaType = mediaType;
		$scope.query();
	}

	
	//选择月份
	$scope.monthChange = function(month) {
		$scope.query(month);
	}
	
	$scope.stopMediaInfoModal = {
		open : function(stopId){
			this.stopId = stopId;
			this.show();
		},
		onShow : function(){
			var mapDiv = "stopMediaInfoModalMapDiv";
			var width = $('#' + mapDiv).width();
			var height = $('#' + mapDiv).height();
			this.map = new AMap.Map(mapDiv, {resizeEnable: true,zoom:13});
			
			
			Page.ajaxGetQuiet('media/stop/' + this.stopId + '/info.do', null, function (resp) {
				$scope.stopMediaInfoModal.mediaStop = resp.data;
				Page.ajaxGetQuiet('media/stop/' + $scope.stopMediaInfoModal.mediaStop.stopId + '/marks.do', null, function (resp) {
					$scope.stopMediaInfoModal.mediaStop.marks = resp.data;
				});
				$("#stopMediaInfoModalImgViewArea").attr("src",$rootScope.nginxPath + $scope.stopMediaInfoModal.mediaStop.stopImg);
				
				if($scope.stopMediaInfoModal.mediaStop){
					
				}
				var stop = $scope.stopMediaInfoModal.mediaStop;
				if(stop.longitude && stop.latitude){
					var marker = new AMap.Marker({
						position: [stop.longitude, stop.latitude],
						title:stop.stopName + '-(' + stop.roadName + '-' + stop.direction + ')',
						map:$scope.stopMediaInfoModal.map
					});
					var infoWindow = new AMap.InfoWindow({offset:new AMap.Pixel(0,-30)});
					marker.on('click',function(e){
						infoWindow.setContent(e.target.getTitle());
						infoWindow.open($scope.stopMediaInfoModal.map, e.target.getPosition());
					});
					$scope.stopMediaInfoModal.map.setCenter([stop.longitude, stop.latitude]);
				}
			});
			
   		}
	};
	
	
	
	
} ]);
